<template>
  <div v-loading="loading" class="app-container">
    <!-- 挂号编号的查询条件开始 -->
    <el-form ref="queryForm" label-width="88px">
      <el-form-item label="挂号单ID" prop="regId">
        <!-- 挂号单号输入框 -->
        <el-input
            v-model="regId"
            clearable
            placeholder="请输入挂号单号"
            size="small"
            style="width:300px"
        />
        <!-- 查询按钮 -->
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <!-- 读取IC卡按钮 -->
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleReadICCard">读取IC卡</el-button>
      </el-form-item>
    </el-form>
    <!-- 挂号编号的查询条件结束 -->

    <!-- 挂号输入框下面的所有内容开始 -->
    <div v-if="careHistory && careHistory.regId">
      <!-- 病例信息部分开始 -->
      <el-card style="margin-bottom: 5px">
        <el-form label-position="right" label-width="120px" inline class="demo-table-expand">
          <!-- 显示挂号单号 -->
          <el-form-item label="挂号单号:">
            <span>{{ careHistory.regId }}</span>
          </el-form-item>
          <!-- 显示医生姓名 -->
          <el-form-item label="医生姓名:">
            <span>{{ careHistory.userName }}</span>
          </el-form-item>
          <!-- 显示科室名称 -->
          <el-form-item label="科室名称:">
            <span>{{ careHistory.deptName }}</span>
          </el-form-item>
          <!-- 显示患者姓名 -->
          <el-form-item label="患者姓名:">
            <span>{{ careHistory.patientName }}</span>
          </el-form-item>
          <!-- 显示就诊时间 -->
          <el-form-item label="就诊时间:">
            <span>{{ careHistory.careTime }}</span>
          </el-form-item>
          <!-- 显示主诉信息 -->
          <el-form-item label="主诉:">
            <span>{{ careHistory.caseTitle }}</span>
          </el-form-item>
          <!-- 显示诊断信息 -->
          <el-form-item label="诊断信息:">
            <span>{{ careHistory.caseResult }}</span>
          </el-form-item>
          <!-- 显示医生建议 -->
          <el-form-item label="医生建议:">
            <span>{{ careHistory.doctorTips }}</span>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 病例信息部分结束 -->

      <!-- 工具按钮部分开始 -->
      <el-card style="margin-bottom: 5px">
        <!-- 全选按钮 -->
        <el-button type="success" icon="el-icon-finished" @click="handleSelectAll">全选</el-button>
        <!-- 取消全选按钮 -->
        <el-button type="success" icon="el-icon-finished" @click="handleUnSelectAll">取消全选</el-button>
        <!-- 现金退费按钮 -->
        <el-button type="danger" icon="el-icon-bank-card" @click="handleBackfeeWithCash">现金退费</el-button>
        <!-- 微信退费按钮 -->
        <el-button type="danger" icon="el-icon-bank-card" @click="handleBackfeeWithWx">微信退费</el-button>
        <!-- 显示订单总额 -->
        <span style="margin-left:20px">订单总额:<span style="color:red;margin-left:20px">￥:{{ allAmount }}</span></span>
      </el-card>
      <!-- 工具按钮部分结束 -->

      <!-- 未支付的处方信息部分开始 -->
      <el-card style="margin-bottom: 5px">
        <el-collapse v-if="careOrders && careOrders.length > 0" v-model="activeNames">
          <!-- 展示每个处方的内容 -->
          <el-collapse-item v-for="(item, index) in careOrders" :key="index" :name="index">
            <template slot="title">
              【药用处方】【{{ index + 1 }}】【处方总额】:￥{{ item.allAmount }}
            </template>
            <el-table
                ref="refTable"
                v-loading="loading"
                border
                :data="item.careOrderItems"
                :row-class-name="tableRowClassName"
                @selection-change="handleCareOrderItemSelectionChange($event, item.coId)"
            >
              <!-- 表格列定义 -->
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="序号" align="center" type="index" width="50"/>
              <el-table-column label="药品名称" align="center" prop="itemName"/>
              <el-table-column label="数量" align="center" prop="num"/>
              <el-table-column label="单价(元)" align="center" prop="price"/>
              <el-table-column label="金额(元)" align="center" prop="amount"/>
              <el-table-column label="备注" align="center" prop="remark"/>
              <el-table-column label="状态" align="center" prop="status" :formatter="statusFormatter"/>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-card>
      <!-- 未支付的处方信息部分结束 -->
    </div>

    <div v-else style="text-align:center">温馨提示：请输入正确的挂号单ID查询</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false, // 页面加载状态
      loadingText: '', // 加载提示文字
      regId: '', // 输入的挂号单ID
      careHistory: {}, // 查询的病例信息
      payStatusOptions: [], // 支付状态字典数据
      careOrders: [], // 未支付的处方信息列表
      activeNames: [], // 当前展开的处方
      orderChargeItems: [], // 订单项列表
      itemObjs: [], // 选择的处方项
      allAmount: 0, // 订单总金额
      payObj: {
        orderId: "" // 当前支付对象的订单ID
      },
      openPay: false, // 是否打开支付二维码
      intervalObj: undefined, // 定时轮询对象
      payResult: {
        orderAmount: 0, // 支付金额
        codeUrl: "", // 支付二维码URL
        orderNo: "" // 订单号
      },
    }
  },
  created() {
    // 初始化支付状态字典数据
    this.StatusName();
  },
  methods: {
    // 查询病例信息
    handleQuery() {
      if (!this.regId) {
        this.$message.warning('请输入挂号单号');
        this.resetCurrentParams();
        return;
      }
      this.loading = true;
      this.loadingText = '数据查询中，请稍后...';

      // 发起查询请求
      this.$http.post(`/charge/selectFee/` + this.regId).then(res => {
        this.loading = false;
        this.loadingText = '';
        const data = res.data.data[0];
        console.log(data);
        if (data) {
          this.careHistory = data;
          this.orderChargeItems = data.orderChargeItems || [];
          this.careOrders = data.careOrders || [];
          this.activeNames = this.careOrders.map((_, index) => index);
        } else {
          this.resetCurrentParams();
          this.$message.error('未找到相关信息');
        }
      }).catch(() => {
        this.$message.error('查询失败');
        this.loading = false;
        this.loadingText = '';
      });
    },
    // 加载支付状态字典数据
    StatusName() {
      this.$http.get("/system/dict/data/type/his_order_details_status").then(resp => {
        this.payStatusOptions = resp.data.data;
      });
    },
    // 读取IC卡功能 (未实现)
    handleReadICCard() {
      this.$message.info('读取IC卡功能尚未实现');
    },
    // 状态格式化函数
    statusFormatter(row) {
      let StatusName = "未知";
      this.payStatusOptions.forEach(item => {
        if (row.status === item.dictValue) {
          StatusName = item.dictLabel;
        }
      });
      return StatusName;
    },
    // 处理处方项选择变化
    handleCareOrderItemSelectionChange(selection, coId) {
      const filteredSelection = selection.map(item => ({...item, coId}));
      this.itemObjs = this.itemObjs.filter(item => item.coId !== coId).concat(filteredSelection);
      this.computeAllAmount();
    },
    // 计算订单总金额
    computeAllAmount() {
      this.allAmount = this.itemObjs.reduce((sum, item) => sum + item.amount, 0);
    },
    // 表格行样式定义
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex;
    },
    // 全选处方项
    handleSelectAll() {
      this.careOrders.forEach((order, index) => {
        const table = this.$refs.refTable[index];
        table.clearSelection();
        table.toggleAllSelection();
      });
    },
    // 取消全选处方项
    handleUnSelectAll() {
      this.careOrders.forEach((order, index) => {
        const table = this.$refs.refTable[index];
        table.clearSelection();
      });
    },
    // 现金退费处理
    handleBackfeeWithCash() {
      if (!this.careHistory.regId) {
        this.$message.warning('请输入挂号单ID查询');
      } else if (this.itemObjs.length === 0) {
        this.$message.warning('请选择要支付的项目');
      } else {
        // 提取与选择的项目相关联的 orderId
        const orderIds = this.itemObjs
            .map(item => item.coId)
            .map(coId => {
              const order = this.orderChargeItems.find(order => order.coId === coId);
              return order ? order.orderId : null;
            })
            .filter(orderId => orderId !== null);

        const orderChargeItemDtoList = this.itemObjs.map(item => ({
          itemId: item.itemId,
          coId: item.coId,
          itemName: item.itemName,
          itemPrice: item.price,
          itemNum: item.num,
          itemType: item.itemType,
          itemAmount: item.amount
        }));

        const postObj = {
          orderAmount: this.allAmount,
          chId: this.careHistory.chId,
          regId: this.careHistory.regId,
          patientName: this.careHistory.patientName,
          createBy: this.careHistory.userName,
          orderChargeItemDtoList: orderChargeItemDtoList,
          orderIds: orderIds
        };
        console.log(postObj);
        this.loading = true;
        this.loadingText = '订单创建并现金退费中';
        this.$confirm('是否确定创建订单并使用现金退费?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post('/charge/backFee/OrderbackFee/', postObj).then(res => {
            if (res.data.code === 200) {
              this.resetCurrentParams();
              this.loading = false;
              this.loadingText = '';
              this.$message.success('退费成功');
              this.handleQuery(); // 刷新数据
            }
          }).catch(() => {
            this.$message.error('退费失败');
            this.loading = false;
            this.loadingText = '';
          });
        }).catch(() => {
          this.loading = false;
          this.loadingText = '';
        });
      }
    },

    // 微信退费处理
    handleBackfeeWithWx() {
      if (!this.careHistory.regId) {
        this.$message.warning('请输入挂号单ID查询');
      } else if (this.itemObjs.length === 0) {
        this.$message.warning('请选择要支付的项目');
      } else {
        // 提取与选择的项目相关联的 orderId
        const orderIds = this.itemObjs
            .map(item => item.coId)
            .map(coId => {
              const order = this.orderChargeItems.find(order => order.coId === coId);
              return order ? order.orderId : null;
            })
            .filter(orderId => orderId !== null);
        console.log(orderIds);
        const orderChargeItemDtoList = this.itemObjs.map(item => ({
          itemId: item.itemId,
          coId: item.coId,
          itemName: item.itemName,
          itemPrice: item.price,
          itemNum: item.num,
          itemType: item.itemType,
          itemAmount: item.amount
        }));

        const postObj = {
          orderAmount: this.allAmount,
          chId: this.careHistory.chId,
          regId: this.careHistory.regId,
          patientName: this.careHistory.patientName,
          createBy: this.careHistory.userName,
          orderChargeItemDtoList: orderChargeItemDtoList,
          orderIds: orderIds
        };
        // 发送请求
        this.loading = true;
        this.loadingText = '订单创建微信退费中';
        this.$confirm('是否确定创建订单并使用微信退费?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post("/charge/backFee/createRefundWx", postObj).then(res => {
            this.resetCurrentParams();
            if (res.data.code === 200) {
              this.$message.success('退费成功');
              this.loading = false;
            }
          })
        }).catch(() => {
          this.$message.info('创建已取消');
          this.loading = false;
        });
      }
    },
    // 重置当前参数
    resetCurrentParams() {
      this.careHistory = {};
      this.careOrders = [];
      this.itemObjs = [];
      this.activeNames = [];
      this.allAmount = 0;
      this.payObj = {};
      this.payResult = { orderAmount: 0, codeUrl: "", orderId: "" };
    }
  }
}
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
